#include "SenseJitterRejection.h"
#include "SensePort.h"
#include "SEGGER_RTT.h"

const unsigned short	s_aChataTmr[ SNS_NUM_MAX_CHATARING ][2] = {
	{ SNS_TIME_ONCHATA_BSENS,	SNS_TIME_OFFCHATA_BSENS 		},	
	{ SNS_TIME_ONCHATA_ASENS,	SNS_TIME_OFFCHATA_ASENS 		},	
};

static	SSNSChataInfo	s_sChataringInfo[ SNS_NUM_MAX_CHATARING ];
static	ESNSStatus	s_eFixStatus[ SNS_NUM_MAX_SENSE ];

void SNS_Init(void)
{
	unsigned char i=0;
	for(i=0;i<SNS_NUM_MAX_CHATARING;i++)
	{
		s_sChataringInfo[i].chataTimer=SNS_TIME_NULL;
		s_sChataringInfo[i].eStatusBuf=SNS_STS_OFF;
	}
	for(i=0;i<SNS_NUM_MAX_SENSE;i++)
	{
		s_eFixStatus[i]=SNS_STS_OFF;
	}
	SensePort_Init();
}

void SNS_execChataRejection(unsigned char port, unsigned int intxms)
{
	SSNSChataInfo	*pInfo;		
	unsigned int	interval;	
	ESNSStatus	eNow;		
	
	interval=intxms;
	
	switch (port){
	case SNS_NUM_BSENS:
		if(SensePort_GetLevel(GPIOA,GPIO_Pin_0)==0)
			eNow=SNS_STS_ON;
		else
			eNow=SNS_STS_OFF;
		break;
	case SNS_NUM_ASENS:
		if(SensePort_GetLevel(GPIOA,GPIO_Pin_1)==0)
			eNow=SNS_STS_ON;
		else
			eNow=SNS_STS_OFF;
		break;
	default:
		return;
	}
	
	pInfo = &s_sChataringInfo[port];
	
	if (eNow != pInfo->eStatusBuf)
	{
		pInfo->eStatusBuf = eNow;	
		if (eNow == OFF)
		{
			if (s_eFixStatus[port] == SNS_STS_OFF){
				pInfo->chataTimer = SNS_TIME_NULL;
			}
			else if (s_eFixStatus[port] == SNS_STS_ON){
				pInfo->chataTimer = s_aChataTmr[port][OFF];
			}
			else {			
				pInfo->chataTimer = s_aChataTmr[port][OFF];    
			}
		}
		else 
		{
			if (s_eFixStatus[port] == SNS_STS_OFF)
			{	
				pInfo->chataTimer = s_aChataTmr[port][ON];
			}
			else if (s_eFixStatus[port] == SNS_STS_ON)
			{		
				pInfo->chataTimer = SNS_TIME_NULL;
			}
			else 
			{		
				pInfo->chataTimer = s_aChataTmr[port][ON];  
			}
		}
		if( pInfo->chataTimer == SNS_TIME_NULL )
		{
			s_eFixStatus[port] = eNow;	
			//SNS_informSenseFix(SNS_convertPortName(port), eNow);
			//SEGGER_RTT_printf(0, "PortNum:%d, eNow = %d\r\n", (unsigned char)port,(unsigned char)eNow);
		}
	}
	else 
	{
		if (pInfo->chataTimer != SNS_TIME_NULL)
		{
			if (pInfo->chataTimer < interval)
			{	
				pInfo->chataTimer = SNS_TIME_NULL;
			}
			else 
			{
				pInfo->chataTimer -= interval;
			}
			if (pInfo->chataTimer == SNS_TIME_NULL)
			{
				s_eFixStatus[port] = eNow;
				//SNS_informSenseFix(SNS_convertPortName(port), eNow);
				SEGGER_RTT_printf(0, "PortNum:%d, eNow = %d\r\n", (unsigned char)port,(unsigned char)eNow);
			}
		}
	}
}
